import { _decorator, Component, instantiate, Label, Node, Prefab } from 'cc';
import { Core } from '../Core/Core';
import { EEquipmentType, EItemAffix, EItemType, IItem } from './Item';
import { BagItem } from './BagItem'; // 引入 BagItem 组件
import { ResourceManager } from '../Core/ResourceManager';
import { PrefabPath } from '../Config/ResourceConfig';
import { Util } from '../Util';
import { Equipment, IEquipment } from './Equipment';
import { EEvent, EPlayerType, ESubView } from '../Config/Enum';
import { EquipmentData } from './EquipmentData';

const { ccclass, property } = _decorator;

@ccclass('EquipmentSwitchView')
export class EquipmentSwitchView extends Component {
    private lbDesc_current: Label;
    private bagItemComp: BagItem; // 引用 BagItem 组件
    private ndCurrentEquipment: Node
    private ndNewEquipment: Node;
    private ndBagContent: Node;
    private NewBagItemComp: BagItem; // 引用 NewBagItem 组件
    private items: IEquipment[] = []; // 存储当前类型的装备物品列表
    private ndButton: Node;
    private equipmentData: EquipmentData;



    ndAffixParent_current: Node;
    ndAffixParent_new: Node;
    ndWuxingAffixParent_current: Node;
    ndWuxingAffixParent_new: Node;
    ndCurrentEquipmentIcon: Node;
    ndNewEquipmentIcon: Node;


    lbDesc_New: Label;
    lbName_new: Label;
    lbAffixes_new: Label;
    lbName_current: Label;
    lbProfession_current: Label;
    lbProfession_new: Label;
    lbAffixes_current: Label;
    newEquipment: Equipment;
    lbDesc_new: Label;
    //ndAffixParent_new: Node;




    protected onLoad(): void {
        //this.ndBG = this.node.getChildByName("BG");
        this.ndCurrentEquipment = this.node.getChildByName("Board").getChildByName("CurrentEquipment").getChildByName("BG");
        this.ndNewEquipment = this.node.getChildByName("Board").getChildByName("NewEquipment").getChildByName("BG");
        this.ndButton = this.node.getChildByName("Button");
        this.ndCurrentEquipmentIcon = this.ndCurrentEquipment.getChildByName("Icon");
        this.ndNewEquipmentIcon = this.ndNewEquipment.getChildByName("Icon");

        

        // 获取 CurrentEquipmentBagItem 节点和组件
        const bagItemNode = this.ndCurrentEquipment.getChildByName("BagItem");
        if (bagItemNode) {
            this.bagItemComp = bagItemNode.getComponent(BagItem);
        }
        // 获取 NewEquipmentBagItem 节点和组件
        const NewBagItemNode = this.ndCurrentEquipment.getChildByName("BagItem");
        if (NewBagItemNode) {
            this.NewBagItemComp = bagItemNode.getComponent(BagItem);
        }


        // 旧的
        this.lbName_current = this.ndCurrentEquipment.getChildByName("Name").getComponent(Label);
        this.lbDesc_current = this.ndCurrentEquipment.getChildByName("Desc").getComponent(Label);
        this.lbProfession_current = this.ndCurrentEquipment.getChildByName("Profession").getComponent(Label);
        this.ndAffixParent_current = this.ndCurrentEquipment.getChildByName("Affixes");
        this.ndWuxingAffixParent_current = this.ndCurrentEquipment.getChildByName("Affixes_Wuxing")
        // 新的
        this.lbName_new = this.ndNewEquipment.getChildByName("Name").getComponent(Label);
        this.ndAffixParent_new = this.ndNewEquipment.getChildByName("Affixes");
        this.lbDesc_new = this.ndNewEquipment.getChildByName("Desc").getComponent(Label);
        this.lbProfession_new = this.ndNewEquipment.getChildByName("Profession").getComponent(Label);
        this.ndWuxingAffixParent_new = this.ndNewEquipment.getChildByName("Affixes_Wuxing")



        this.ndBagContent = this.node.getChildByName("Bag_EquipmentSwitch").getChildByName("ScrollView").getChildByName("view").getChildByName("content");


        
        // 获取 BagItem 节点和组件
        // const bagItemNode = this.node.getChildByName("Board").getChildByName("BagItem");
        // if (bagItemNode) {
        //     this.bagItemComp = bagItemNode.getComponent(BagItem);
        // }
        
        // this.lbDesc = this.node.getChildByName("Board").getChildByName("Desc").getComponent(Label);
        // this.affixParent = this.node.getChildByName("Board").getChildByName("Affixes");

        //this.ndButton.active = false; // 初始时隐藏按钮
    }

    protected onEnable(): void {
        Core.Instance.currentSubView = ESubView.EquipmentSwitch;
        console.log("EquipmentSwitchView onEnable Core.Instance.currentPlayer", Core.Instance.currentPlayer);
        console.log("EquipmentSwitchView onEnable Core.Instance.currentEquipmentType", Core.Instance.currentEquipmentType);
        console.log("EquipmentSwitchView onEnable Core.Instance.players.get(Core.Instance.currentPlayer).equipmentData",Core.Instance.players.get(Core.Instance.currentPlayer).equipmentData);
        this.equipmentData = Core.Instance.players.get(Core.Instance.currentPlayer).equipmentData
    
        this.getEquipmentByType();

        //加载当前的装备信息在ndCurrentEquipment
        this.loadCurrentEquipment();
        this.unloadNewEquipment(); // 确保新装备区域是空的


    }

    protected onDisable(): void {
        ///this.unloadNewEquipment()
        //this.unloadCurrentEquipment();
        //this.ndBG.off(Node.EventType.TOUCH_END, this.onButtonCloseWindow, this);
        this.newEquipment = null
        this.node.destroy();

    }

    // 当前装备出现在左边
    loadCurrentEquipment(){
        console.log("加载当前装备信息 loadCurrentEquipment");
        this.unloadCurrentEquipment(); // 清除之前的装备信息

        const currentEquipment = this.equipmentData.equipped.get(Core.Instance.currentEquipmentType);
        if (!currentEquipment) {
            console.log("当前位置玩家没有装备:", Core.Instance.currentEquipmentType);
            // 选一个同类型的装备放到newEquipment

            console.log("选一个同类型的装备放到newEquipmentthis.items", this.items);

            //this.loadNewEquipment("BagItem1")
            return
        }
        const prefab = ResourceManager.Instance.getResourceCache().get(PrefabPath.BagItem) as Prefab;
        const bagItemNode = instantiate(prefab);
        bagItemNode.setParent(this.ndCurrentEquipmentIcon);
        bagItemNode.setPosition(0,0);
        const bagItemComp = bagItemNode.getComponent(BagItem);
        bagItemComp.init(currentEquipment);



        // 显示物品描述
        this.lbDesc_current.string = currentEquipment.desc || "无描述";
        this.lbName_current.string = currentEquipment.name || "无名称";
        this.lbProfession_current.string = this.showProfessionRestrictions(currentEquipment)



        // 根据物品类型处理特殊信息（如装备词缀）
        if (currentEquipment.itemType === EItemType.Equipment || currentEquipment.itemType === EItemType.Gem) {
            this.showAffixes(currentEquipment, this.ndAffixParent_current);
            this.showWuxingAffixes(currentEquipment, this.ndWuxingAffixParent_current);
        }
    }

    
    // 新装备出现在右边
    loadNewEquipment(value: string) {
        console.log("加载新装备信息 loadNewEquipment", value);
        this.unloadNewEquipment(); // 清除之前的装备信息

        let num = Util.extractNumberFromEnd(value)-1
        console.log("加载新装备信息,选择的装备格子num:", num);
        this.newEquipment = this.items[num] as Equipment;
        console.log("加载新装备信息,新装备:", this.newEquipment);
        if (!this.newEquipment) {return}

        //this.unloadNewEquipment(); // 清除之前的装备信息
        //Core.Instance.bag.removeItem(this.newEquipment); // 从背包中移除当前选择的装备
        console.log("移除后的背包物品:", Core.Instance.bag.getItems());
        this.getEquipmentByType();

        const prefab = ResourceManager.Instance.getResourceCache().get(PrefabPath.BagItem) as Prefab;
        const bagItemNode = instantiate(prefab);
        bagItemNode.setParent(this.ndNewEquipmentIcon);
        bagItemNode.setPosition(0,0);
        bagItemNode.getComponent(BagItem).init(this.newEquipment);


        // 显示物品描述
        this.lbDesc_new.string = this.newEquipment.desc || "无描述";
        this.lbName_new.string = this.newEquipment.name || "无名称";
        this.lbProfession_new.string = this.showProfessionRestrictions(this.newEquipment)


        // 显示词缀
        if (this.newEquipment.itemType === EItemType.Equipment || this.newEquipment.itemType === EItemType.Gem) {
            this.showAffixes(this.newEquipment, this.ndAffixParent_new);
            this.showWuxingAffixes(this.newEquipment, this.ndWuxingAffixParent_new);
        }


        this.ndButton.active = true; // 显示按钮
        


    }

    unloadCurrentEquipment() {
        console.log("卸载当前装备信息 unloadCurrentEquipment");
        // 清除当前装备信息
        if(this.ndCurrentEquipment.getChildByName("BagItem")){this.ndCurrentEquipment.getChildByName("BagItem").destroy()};
        this.lbDesc_current.string = ""; // 清除描述
        this.lbName_current.string = ""; // 清除名称
        this.lbProfession_current.string = ""; // 清除职业限制

        this.ndAffixParent_current.children.forEach(node => node.active = false); // 隐藏所有词缀节点
        this.ndWuxingAffixParent_current.children.forEach(node => node.active = false); // 隐藏所有五行词缀节点
    }

    unloadNewEquipment() {
        console.log("卸载新装备信息 this.ndNewEquipment:", this.ndNewEquipment);
        // 将装备加回背包
        // if (this.newEquipment) {
        //     Core.Instance.bag.addItem(this.newEquipment);
        //     this.newEquipment = null; // 清除当前选择的装备引用
        //     this.getEquipmentByType();
        // }
        if(this.ndNewEquipmentIcon.getChildByName("BagItem")){this.ndNewEquipmentIcon.getChildByName("BagItem").destroy()};
        this.lbDesc_new.string = ""; // 清除描述
        this.lbName_new.string = ""; // 清除名称
        this.lbProfession_new.string = ""; // 清除职业限制
        this.ndAffixParent_new.children.forEach(node => node.active = false); // 隐藏所有词缀节点
        this.ndWuxingAffixParent_new.children.forEach(node => node.active = false); // 隐藏所有五行词缀节点
        //this.newEquipment = null
    }





    private showAffixes(equipment: IEquipment, affixParent): void {
        // 隐藏所有词缀节点
        affixParent.children.forEach(node => node.active = false);
        
        // 显示当前装备的词缀
        if (equipment.affixes && equipment.affixes.length > 0) {
            for (let i = 0; i < equipment.affixes.length; i++) {
                const affixNode = affixParent.children[i];
                if (affixNode) {
                    affixNode.getComponent(Label).string = equipment.affixes[i].description;
                    affixNode.active = true;
                }
            }
        }
    }


    private showWuxingAffixes(equipment: IEquipment, affixParent): void {
        // 隐藏所有词缀节点
        affixParent.children.forEach(node => node.active = false);
        
        // 显示当前装备的词缀
        if (equipment.affixes_wuxing && equipment.affixes_wuxing.length > 0) {
            for (let i = 0; i < equipment.affixes_wuxing.length; i++) {
                const affixNode = affixParent.children[i];
                if (affixNode) {
                    affixNode.getComponent(Label).string = equipment.affixes_wuxing[i].description;
                    affixNode.active = true;
                }
            }
        }
    }
    createBagItem() {
        console.log("创建背包格子节点");

        // 清除现有节点（可选，根据需求决定）
        this.ndBagContent.removeAllChildren();
        
        // 获取BagItem预制体
        const prefab = ResourceManager.Instance.getResourceCache().get(PrefabPath.BagItem) as Prefab;
        
        // 创建指定数量的背包格子
        for (let i = 0; i < Core.Instance.maxBag; i++) {
            const bagItemNode = instantiate(prefab);
            bagItemNode.name = `BagItem${i + 1}`; // 设置名称：BagItem1, BagItem2...
            this.ndBagContent.addChild(bagItemNode);
        }
    }
    // 获取此类装备列表
    getEquipmentByType(){
        console.log("获取此类装备列表Core.Instance.currentEquipmentType:", Core.Instance.currentEquipmentType);

        this.items = Core.Instance.bag.getEquipmentByType(Core.Instance.currentEquipmentType);
        console.log("获取到的此类装备物品:", this.items);

        // 确保每个物品都是 Equipment 实例
        // this.items = rawItems.map(item => {
        //     if (item instanceof Equipment) {
        //         return item; // 已经是实例，直接返回
        //     } else {
        //         return new Equipment(item as IEquipment); // 转换为 Equipment 实例
        //     }
            
        // });
        this.createBagItem(); // 重新创建背包格子节点
        // 遍历所有装备物品
        for (let i = 0; i < this.items.length; i++) {
            const item = this.items[i];
            console.log("getEquipmentByType当前装备物品:", item);
            const bagItemNode = this.ndBagContent.children[i];
            //const bagItemNode = instantiate(ResourceManager.Instance.getRes<Node>(EPath.Prefab.BagItem));
            const bagItemComp = bagItemNode.getComponent(BagItem);
            bagItemComp.init(item);
            this.ndBagContent.addChild(bagItemNode);
        }

    }

    private onButtonCloseWindow(): void {
        this.node.active = false;
    }

    onButtonSwitchEquipment(): void {
        console.log("switchEquipment");


        if (this.newEquipment) {
            // 检查一下装备职业限制
            // if(this.checkProfessionRestriction(this.newEquipment)){
            //     Core.Instance.showTips("职业不符");
            //     return
            // }
            if(this.newEquipment.equipmentType === EEquipmentType.Weapon){
                const profession = this.newEquipment.profession;
                const currentPlayerType = Core.Instance.players.get(Core.Instance.currentPlayer).playerType;
                console.log("检查职业限制 equipment.profession:", profession, "currentPlayerType:", currentPlayerType , "profession.indexOf(currentPlayerType)",profession.indexOf(currentPlayerType));
                // 日志显示 ： 检查职业限制 equipment.profession: [] currentPlayerType: Tangmen profession.indexOf(currentPlayerType) -1
                if (profession.indexOf(currentPlayerType) === -1) {
                    Core.Instance.showTips("职业不符");
                    return;
                }
            }

            // 切换装备
            // 将新装备放入装备栏





            // 原来的装备放入背包
            if( this.equipmentData.equipped.get(Core.Instance.currentEquipmentType)){
                Core.Instance.bag.addItem(this.equipmentData.equipped.get(Core.Instance.currentEquipmentType))
                    // 使用 forEach 遍历并修改
                    this.equipmentData.equipped.get(Core.Instance.currentEquipmentType).affixes_wuxing.forEach((affix: EItemAffix) => {
                        affix.isActive = false;
                        console.log("切换装备后的背包物品affix.isActive:",affix.isActive);
                    });
                    
            }

            
            
            this.equipmentData.equipped.set(Core.Instance.currentEquipmentType, this.newEquipment);

            // 激活一下五行词缀
            this.equipmentData.activateWuxingAffixes();


            console.log("3切换装备后的背包物品this.newEquipment:",this.newEquipment);
            Core.Instance.bag.removeItem(this.newEquipment as IItem); // 从背包中移除当前选择的装备
            console.log("3切换装备后的背包物品:", Core.Instance.bag.getItems());
            console.log("4切换装备后的背包物品this.newEquipment:",this.newEquipment);

            this.loadCurrentEquipment(); // 刷新当前装备显示
            this.getEquipmentByType(); // 刷新背包中的装备列表
            this.unloadNewEquipment(); // 清除新装备显示
            Core.Instance.event.emit(EEvent.EquipmentChanged); // 触发装备变化事件,更新展示
            this.newEquipment.isEquipped = true; // 标记为已装备
            //Core.Instance.save()



        }
    }
    // 检查职业限，如果
    // checkProfessionRestriction(equipment: Equipment): boolean {
    //     const profession = equipment.profession;
    //     const currentPlayerType = Core.Instance.players.get(Core.Instance.currentPlayer).playerType;
    //     console.log("检查职业限制 equipment.profession:", profession, "currentPlayerType:", currentPlayerType , "profession.indexOf(currentPlayerType)",profession.indexOf(currentPlayerType));

    //     return profession.indexOf(currentPlayerType) !== -1;
    // }

        private showProfessionRestrictions(equipment: IEquipment) {
            let result = ""
            
        
            // 如果是武器，则显示职业限制
            if (equipment.equipmentType == EEquipmentType.Weapon) {
                let profession = equipment.profession
                switch(profession){
                    case []:
                        result= "通用"
                        break;
                    default:
                        let s = "适合:"
                        for (const p of profession) {
                            let pro = Core.Instance.getProfessionDesc(p as EPlayerType)
                            s += pro + " "
                        }
                        result = s
                        break;
    
                            
                }
            }else{
                result = ""
            }

            return result;
        }

}